package cn.cvs.controller;

import cn.cvs.pojo.TSysRole;
import cn.cvs.pojo.TSysUser;
import cn.cvs.service.RoleService;
import cn.cvs.service.UserService;
import cn.cvs.utils.Constants;
import cn.cvs.utils.Page;
import com.alibaba.fastjson.JSON;
import com.mysql.cj.log.Log;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController { //UserAction  -->  execute()

    @Resource
    UserService userService;

    @Resource
    RoleService roleService;

    @RequestMapping("/tologin")
    public String tologin(){
        return "login";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute(Constants.userSession);
        return "login";
    }


    @RequestMapping({"/dologin","/login"})  //loginAction -->Spring  Struts2(Web)   Mybatis(dao)
    public String dologin(
            @RequestParam(value = "account") String username
            , @RequestParam String password
            , HttpServletRequest request
            , HttpSession session
            ){

        TSysUser user = null;
        try {
            user = userService.login(username,password);
            if (null != user){
                //session.setAttribute(Constants.USER_SESSION,username);
                session.setAttribute(Constants.userSession,user);
                return "redirect:/user/toMain";
                // response.sendRedirect("/user/toMain");
            }else{
                request.setAttribute("error","账密不存在");
                request.setAttribute("account",username);
                request.setAttribute("password",password);
                return "login";
            }

        } catch (Exception exception) {
            exception.printStackTrace();
            request.setAttribute("error",exception.getMessage());
            return "login";
        }

//        if ("admin".equals(username) && "123456".equals(password)){

    }
    @RequestMapping("/toMain")
    public String main(HttpSession session){
        if (null == session.getAttribute(Constants.userSession) ){
            return "redirect:/user/tologin";
        }
        return "frame";
    }

    @RequestMapping("/list")
    public String list(Model model
                            ,HttpSession session
                            ,HttpServletRequest request
                            ,@RequestParam(required = false) String queryRealName
                            ,@RequestParam(defaultValue = "0") Long queryRoleId
                            ,@RequestParam(defaultValue = "1") Integer pageIndex){
        //前期的数据准备
        //查所有的角色列表
        try {
            List<TSysRole> roleList= roleService.getAllRole();
            model.addAttribute("roleList",roleList);

            //查询所有的用户信息 + 分页
            int pageSize =Constants.pageSize;
       /* System.out.println("queryRealName: "+queryRealName);
        System.out.println("queryRoleId: "+ Long.valueOf(queryRoleId));
        TSysUser userParam =new TSysUser();
        if (null!=queryRealName && null != queryRoleId){
            userParam = new TSysUser(queryRealName,Long.valueOf(queryRoleId));
        }*/

            TSysUser userParam =new TSysUser();
            userParam.setRealName(queryRealName);
            userParam.setRoleId(queryRoleId);
            int totalCount =userService.getUserCount(userParam);


            List<TSysUser> userList=userService.getUserByRoleIdPage(queryRealName,queryRoleId,pageIndex,pageSize);

            Page page =new Page();
            page.setCurrPageNo(pageIndex);
            page.setPageSize(pageSize);
            page.setTotalCount(totalCount);

            int totalPageCount= page.getTotalPageCount();
            if (pageIndex >totalPageCount) pageIndex=totalPageCount;
            model.addAttribute("totalPageCount",totalPageCount);
            model.addAttribute("totalCount",totalCount);
            model.addAttribute("currentPageNo",pageIndex);
            model.addAttribute("totalPageCount",totalPageCount);
            model.addAttribute("queryRealName",queryRealName);
            model.addAttribute("queryRoleId",queryRoleId);
            model.addAttribute("userList",userList);
        } catch (Exception exception) {
            exception.printStackTrace();
            session.setAttribute("error",exception.getMessage());
            return "redirect:/user/error";
        }
        return "sysUser/list";
    }

    @RequestMapping("/error")
    public String error(){
        return "error";
    }

    @RequestMapping("/toAdd")
    public String toAdd(){
        System.out.println("=========>toAdd");
        return "sysUser/add";
    }

    @PostMapping("/add")
    public String add(TSysUser sysUser
                        , HttpServletRequest request
                       //,  @RequestParam(value = "idPic" ,required = false) MultipartFile idPic
                       //,  @RequestParam(value = "workPic" ,required = false) MultipartFile workPic
                       ,  @RequestParam(value = "attachs" ,required = false) MultipartFile[] attachs
                      ){
        System.out.println("---->doAdd");

        //文件上传
        String idPicPath =null;//映射实体类
        String workPicPath =null;//映射实体类
        String path =""; //获取服务器地址
        System.out.println("path: "+ path);
        File file =null;
        //idPic
        if (null!=attachs && attachs.length>0){
           // path = request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
            path = request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploads");
            //path = request.getContextPath();
            file = new File(path);
            if (!file.exists()) file.mkdir() ;//不存在则创建该路径
        }
        for (int i = 0; i <attachs.length ; i++) {
            MultipartFile idPic =attachs[i];
            if (null!=idPic && idPic.getSize()>0){
                try {
                    //解析文件
                    String originalFile = idPic.getOriginalFilename();//原文件名
                    String suffix =FilenameUtils.getExtension(originalFile);//originalFile.substring(originalFile.lastIndexOf(".")+1);
                    //处理文件名
                    String fileName =System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"t317cvs_Personal."+suffix;
                    //上传  格式以及大小的验证,放到jsp验证
                    idPic.transferTo(new File(file,fileName));
                    //   /statics/uploadfiles/fileName

                    if (i==0){
                        idPicPath =File.separator+"statics"+ File.separator+"uploads"+ File.separator+fileName;
                    }else if(i==1){
                        workPicPath =File.separator+"statics"+ File.separator+"uploads"+ File.separator+fileName;
                    }
                } catch (IOException exception) {
                    exception.printStackTrace();
                    request.setAttribute("uploadFileError","证件照上传失败"+ exception.getMessage());
                }
            }
        }


        try {
            //添加 普通字段
            //取出Session中当前登录的用户的id,set到createdUserId中
            sysUser.setCreatedUserId(((TSysUser)request.getSession().getAttribute(Constants.userSession)).getId());
            sysUser.setIdPicPath(idPicPath);//图片路径更新到数据中
            sysUser.setWorkPicPath(workPicPath);
            if(userService.addUser(sysUser)){
                return "redirect:/user/list"; //成功
            }
            request.setAttribute("error","添加失败");
            return "sysUser/add";  //失败
        } catch (Exception exception) {
            exception.printStackTrace();
            request.setAttribute("error","添加失败"+ exception.getMessage());
            return "error";  //失败
        }

    }


    //@RequestMapping("toUpdate")
    @GetMapping("/toUpdate/{id}")
    public String toUpdate(@PathVariable String id,Model model,HttpServletRequest request){
        System.out.println("=========>toUpdate,id: "+ id);
        //根据id查找对应的用户信息,用户信息要传入 update.jsp中
        try {
            TSysUser param = new TSysUser();
            param.setId(Long.valueOf(id));
            System.out.println(param);
            List<TSysUser> ulist = userService.getUserListByPojo(param);

//            String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");

            if (null!=ulist && ulist.size()>0){
                param = ulist.get(0);
                String idPicPath = param.getIdPicPath();
                String workPicPath = param.getWorkPicPath();

                // 图片路径加上项目的环境目录
                if (null !=idPicPath && !"".equals(idPicPath)){
                    param.setIdPicPath(idPicPath);
                }
                if (null !=workPicPath && !"".equals(workPicPath)){
                    param.setWorkPicPath(workPicPath);
                }

                System.out.println("=====================>>>"+param.getWorkPicPath());
            }

            //用户角色
            List<TSysRole> roleList = roleService.getAllRole();

            model.addAttribute("sysUser",param); // .addAttribute(""param",param);
            model.addAttribute("roleList",roleList); // .addAttribute(""param",param);
            return "sysUser/update";
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return "error";
        }
    }

    @RequestMapping("update")
    public String update(TSysUser sysUser,HttpServletRequest request){
        System.out.println("---->doUpdate");
        try {
            //添加 普通字段
            //取出Session中当前登录的用户的id,set到updatedUserId中
            sysUser.setUpdatedUserId(((TSysUser)request.getSession().getAttribute(Constants.userSession)).getId());
            if(userService.updateUser(sysUser)){
                return "redirect:/user/list"; //成功
            }
            request.setAttribute("error","修改失败");
            return "sysUser/update";  //失败
        } catch (Exception exception) {
            exception.printStackTrace();
            request.setAttribute("error","修改失败"+ exception.getMessage());
            return "error";  //失败
        }
    }

    @ResponseBody  //响应的数据是ajax的请求
//    @RequestMapping("/view/{id}")
    @RequestMapping(value = "/{id}/view")//,produces = {"application/json;charset=UTF-8"}) //json html xml
    public Object viewUser(@PathVariable Integer id,Model model){
        String sysUserJson="";
        TSysUser sysUser =null;
        if (null !=id && id>0) {
            List<TSysUser> userList = userService.getUserListByPojo(new TSysUser(Long.valueOf(id)));
            if (null!=userList && userList.size()>0){
                 sysUser =userList.get(0);
                System.out.println(sysUser);
                //model.addAttribute("sysUser",sysUser);
                //sysUserJson = JSON.toJSONString(sysUser);
            }else{
                return "nodata";
            }
        }else {
            return "nodata";
        }
//        return "sysUser/view";
        //return sysUserJson;
        return sysUser;

    }
}
